import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应格式
        resp.setContentType("application/json; charset=utf8");
        req.setCharacterEncoding("utf8");
        //获取响应中的query string (这里是blogId)
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        if(blogId == null) {//获取博客列表
            //1.从数据库中取出博客列表数据
            List<Blog> blogList = blogDao.getBlogList();
            //2.返回响应
            resp.getWriter().write(objectMapper.writeValueAsString(blogList));
        } else {//博客详情页
            //1.根据博客ID从数据库中取出对应博客
            Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
            //2.返回博客
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    //发布博客

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应和请求格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.从请求中获取博客标题和内容
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //2.获取当前会话（获取userId）
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录！");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录！");
            return;
        }
        //3.创建Blog数据
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        //4.将blog数据存放到数据库
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //5.重定向到主页
        resp.sendRedirect("blog_list.html");
    }
}
